package com.example.bilibili_miaosha.config;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.bilibili_miaosha.entity.User;
import com.example.bilibili_miaosha.service.IUserService;
import com.example.bilibili_miaosha.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName UserArgumentResolver
 * @Description TODO：保存在自己的经验库里面
 * @Author 川
 * @Date 2022/4/9 15:31
 * @Version 1.0
 **/
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private IUserService userService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Class<?> clazz = parameter.getParameterType();
        return clazz == User.class;
    }

    @Override
    /** 
    * @Description: TODO：每个页面都能传递user的核心原因啊！！！！！
     * todo: 没有实现未登录用户直接跳转到登录页面。（是不是应该放在前端啊）
    * @Param: [parameter, mavContainer, webRequest, binderFactory] 
    * @return: java.lang.Object 
    * @Author: 弓川
    * @Date: 2022/4/9 
    **/ 
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request =        webRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response =           webRequest.getNativeResponse(HttpServletResponse.class);
        String ticket = CookieUtil.getCookieValue(request, "userTicket");
        System.out.println("经过了 resolveArgument");
        if (StringUtils.isEmpty(ticket)) {

            return null;
        }
        User user = userService.getByUserTicket(ticket, request, response);
        user.setNickname("hhhhhh");
        return user;
    }
}